<template>
  <view class="container">
    <view class="header fixed-header">
		<view class="search">
			<input class="search-input" placeholder="请输入设备名称" v-model="searchQuery" @confirm="searchDevices" />
			<view class="blank"></view>
			<button class="search-button" @click="searchDevices">搜索</button>
		</view>
	  <button class="add-device-button" @click="addDevice">添加设备</button>
    </view>
    <scroll-view class="device-list" scroll-y="true">
      <view class="device-card" v-for="device in filteredDevices" :key="device.id" @click="showDeviceActions(device)">
        <view class="device-info">
			
          <text class="device-id">{{device.id}}</text>
          <text class="device-type">{{device.type}}</text>
          <text class="device-status">{{device.status}}</text>
        </view>
        <view class="device-info">
		  <text class="device-name" @click.stop="goToDeviceDetail(device.id)">{{device.name}}</text>
          <text class="device-unit">{{device.unit}}</text>
        </view>
		<view class="device-info">
		  <switch @change="handleControlChange($event, device.id)" :checked="device.isControlEnabled" @click.stop />
		  <text class="control-time">{{device.controlTime}}</text>
		  <text class="control-type">{{device.area}}</text>
		</view>
        <view class="device-status">
          <text class="status">{{device.controlStatus}}</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- Popup Menu for Device Actions -->
    <view class="popup-overlay" v-if="showActionPopup" @click="closePopup"></view>
    <view class="action-popup" v-if="showActionPopup">
      <view class="popup-header">
        <text class="popup-title">设备操作</text>
        <text class="popup-close" @click="closePopup">×</text>
      </view>
      <view class="popup-content">
        <view class="popup-device-info">
          <view class="input-group">
            <text class="input-label">设备名称:</text>
            <input class="edit-input" v-model="editingDevice.name" placeholder="输入设备名称" />
          </view>
          <view class="input-group">
            <text class="input-label">设备类型:</text>
            <input class="edit-input" v-model="editingDevice.type" placeholder="输入设备类型" />
          </view>
          <view class="input-group">
            <text class="input-label">设备单位:</text>
            <input class="edit-input" v-model="editingDevice.unit" placeholder="输入设备单位" />
          </view>
          <view class="input-group">
            <text class="input-label">控制类型:</text>
            <input class="edit-input" v-model="editingDevice.area" placeholder="输入控制类型" />
          </view>
          <view class="input-group">
            <text class="input-label">状态:</text>
            <view class="edit-input status-display">{{editingDevice.status}}</view>
          </view>
        </view>
        <view class="action-buttons">
          <button class="action-button edit-button" @click="saveDeviceChanges">保存</button>
          <button class="action-button delete-button" @click="confirmDeleteDevice">删除设备</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import deviceApi from '@/pages/common/deviceApi.js';
export default {
  data() {
    return {
      searchQuery: '',
      devices: [], // 设备列表初始化为空
      showActionPopup: false,
      selectedDevice: null,
      editingDevice: null,
      statusIndex: 0,
      statusOptions: ['在线', '离线']
    };
  },
  computed: {
    filteredDevices() {
      if (!this.searchQuery) {
        return this.devices;
      }
      const query = this.searchQuery.toLowerCase();
      return this.devices.filter(device => 
        (device.name || '').toLowerCase().includes(query) || 
        (device.type || '').toLowerCase().includes(query) ||
        (device.unit || '').toLowerCase().includes(query)
      );
    }
  },
  created() {
    this.loadDevices();
  },
  methods: {
    async loadDevices() {
      try {
        uni.showLoading({ title: '加载中...' });
        const res = await deviceApi.getDeviceList();
        uni.hideLoading();
        if (res && res.data && res.data.success) {
          // 兼容后端返回格式
          this.devices = res.data.result.records || res.data.result || [];
        } else {
          this.devices = [];
          uni.showToast({ title: res?.data?.message || '获取设备失败', icon: 'none' });
        }
      } catch (e) {
        uni.hideLoading();
        this.devices = [];
        uni.showToast({ title: '接口异常', icon: 'none' });
      }
    },
    searchDevices() {
      console.log('搜索设备:', this.searchQuery);
      // 搜索逻辑已在 computed 属性中实现
      
      if (this.filteredDevices.length === 0) {
        uni.showToast({
          title: '未找到符合条件的设备',
          icon: 'none'
        });
      }
    },
    
    addDevice() {
      console.log('添加设备按钮点击');
      uni.navigateTo({
        url: '/pages/device/add'
      });
    },
    
    goToDeviceDetail(deviceId) {
      const device = this.devices.find(d => d.id === deviceId);
      if (!device) {
        uni.showToast({
          title: '设备不存在',
          icon: 'none'
        });
        return;
      }
      // 使用encodeURIComponent对参数进行编码，防止特殊字符导致的问题
      const params = {
        id: deviceId,
        name: encodeURIComponent(device.name),
        type: encodeURIComponent(device.type),
        status: encodeURIComponent(device.status),
        unit: encodeURIComponent(device.unit),
        controlTime: encodeURIComponent(device.controlTime),
        area: encodeURIComponent(device.area),
        controlStatus: encodeURIComponent(device.controlStatus),
        isControlEnabled: device.isControlEnabled
      };
      
      uni.navigateTo({
        url: `/pages/device/detail?${Object.entries(params)
          .map(([key, value]) => `${key}=${value}`)
          .join('&')}`
      });
    },
    
    handleControlChange(event, deviceId) {
      const device = this.devices.find(d => d.id === deviceId);
      if (device) {
        device.isControlEnabled = event.detail.value;
        device.controlStatus = device.isControlEnabled ? '操控正常' : '操控异常';
        console.log(`设备 ${deviceId} 远程操控状态已更改为: ${device.isControlEnabled ? '启用' : '禁用'}`);
      }
    },
    
    showDeviceActions(device) {
      this.selectedDevice = device;
      this.editingDevice = { ...device };
      this.statusIndex = this.statusOptions.indexOf(device.status);
      this.showActionPopup = true;
    },
    
    closePopup() {
      this.showActionPopup = false;
    },
    
    saveDeviceChanges() {
      if (!this.editingDevice) return;
      
      // Update the device in the local array
      const index = this.devices.findIndex(d => d.id === this.editingDevice.id);
      if (index !== -1) {
        this.devices[index] = { ...this.editingDevice };
        uni.showToast({
          title: '设备信息已更新',
          icon: 'success'
        });
      }
      
      this.closePopup();
    },
    
    confirmDeleteDevice() {
      if (!this.selectedDevice) return;
      
      // Close the editing popup first
      this.showActionPopup = false;
      
      // Show delete confirmation dialog
      uni.showModal({
        title: '删除确认',
        content: `确定要删除设备 "${this.selectedDevice.name}" 吗？此操作不可撤销。`,
        confirmColor: '#FF0000',
        success: (res) => {
          if (res.confirm) {
            this.deleteDevice(this.selectedDevice.id);
          }
        }
      });
    },
    
    deleteDevice(deviceId) {
      // In a real app, you would call an API to delete the device
      // For this example, we'll just remove it from the local array
      const index = this.devices.findIndex(d => d.id === deviceId);
      if (index !== -1) {
        this.devices.splice(index, 1);
        uni.showToast({
          title: '设备已删除',
          icon: 'success'
        });
      }
      
      // No need to close popup here as it's already closed
    },
    
    handleStatusChange(event) {
      const index = event.detail.value;
      this.statusIndex = index;
      this.editingDevice.status = this.statusOptions[index];
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #f2f2f2;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  position: relative;
}
.header {
  position: fixed;
  width: 670rpx;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  background-color: white;
  border-radius: 10rpx;
  box-shadow: 
	10rpx 10rpx gainsboro
  ;
  z-index: 999;
}
.title {
  font-size: 24px;
  font-weight: bold;
}
.search{
	display: flex;
	align-items: center;
	flex-direction: row;
	width: auto;
	margin: 10rpx;
	}
.blank{
	width: 100rpx;
}
.search-input {
  width: 200px;
  height: 30px;
  margin-right: 10px;
  border-width: 1rpx;
  border-color: black;
  border-radius: 20rpx;
  background-color: #f2f2f2;

}
.search-button {
  text-align: center;
  color: white;
  height: 40px;
  width: 100px;
  border-radius: 40rpx;
  line-height: 40px;
  background-color: #007aff;
}
.add-device-button {
  margin: 20px;
  width: 600rpx;
  height: 40px;
  background-color: #007aff;
  color: white;
  text-align: center;
  line-height: 40px;
  border-radius: 40rpx;
}
.device-list {
  flex: 1;
  margin-top: 290rpx;
  margin-left: 1rpx;
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: absolute;
  top: 0;
  bottom: 20rpx;
  width: 100%;
}
.device-card {
  width: 620rpx;
  background-color: white;
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 5px;
  box-shadow:
  	10rpx 10rpx gainsboro
  ;
}
.device-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}
.device-name, .device-type, .device-status, .device-unit, .control-time, .control-type {
  font-weight: bold;
}
.device-status {
  color: red;
  text-align: center;
  font-size: 24rpx;
}
.device-info switch {
  transform: scale(0.8);
  margin: 0 10rpx;
}
.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}
.action-popup {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  max-width: 400px;
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  z-index: 1000;
  max-height: 80vh;
  overflow-y: auto;
}
.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.popup-title {
  font-size: 24px;
  font-weight: bold;
}
.popup-close {
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
}
.popup-content {
  margin-bottom: 20px;
  z-index: 1000;
  position: relative;
}
.popup-device-info {
  margin-bottom: 10px;
  z-index: 1001;
  position: relative;
}
.input-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  position: relative;
  z-index: 1002;
}
.input-label {
  width: 100px;
  font-weight: bold;
}
.edit-input {
  width: 200px;
  height: 30px;
  border-width: 1rpx;
  border-color: black;
  border-radius: 10cap;
  position: relative;
  z-index: 1001;
}
picker {
  z-index: 9999 !important; 
  position: relative !important;
}
.picker-view {
  width: 100%;
  height: 30px;
  line-height: 30px;
  text-align: left;
  padding-left: 10px;
  z-index: 9999;
  position: relative;
}
.action-buttons {
  display: flex;
  justify-content: space-between;
}
.action-button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.edit-button {
  background-color: #007aff;
  color: white;
}
.delete-button {
  background-color: red;
  color: white;
}
.status-display {
  padding-left: 10px;
  display: flex;
  align-items: center;
}
</style> 